package com.zhz.project.main.socolar.wenzhang;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.ibatispage.IbatisPage;
import com.zhz.project.common.util.result.Result;
import com.zhz.project.common.util.result.ResultSupport;
import com.zhz.project.dal.daointerface.IssueDAO;
import com.zhz.project.dal.daointerface.WenzhangDAO;
import com.zhz.project.dal.dataobject.IssueDO;
import com.zhz.project.dal.dataobject.WenzhangDO;
import com.zhz.project.main.socolar.wenzhang.util.GetCookieKey;
import com.zhz.project.main.socolar.wenzhang.util.SocolarWenzhangParser;
import com.zhz.project.util.getWebContent;

public class SocolarWenzhangMain implements Runnable {
    private static Log   logger = LogFactory.getLog(SocolarWenzhangMain.class);

    public static String url    = "http://www.socolar.com/";

    private int          pageNo;

    public SocolarWenzhangMain(int pageNo) {
        this.pageNo = pageNo;
    }

    public void run() {
        init(pageNo);
    }

    public void init(int pageNo) {

        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            new String[] { "ibatis-spring.xml" });

        //卷期DAO
        IssueDAO issueDAO = (IssueDAO) appContext.getBean("issueDAO");

        //文章DAO
        WenzhangDAO wenzhangDAO = (WenzhangDAO) appContext.getBean("wenzhangDAO");

        //查詢需要處理的卷期
        IbatisPage page = (IbatisPage) appContext.getBean("ibatisPage");

        Map map = new HashMap();
        map.put("indexPage", pageNo + "");
        Map result = page.getPage(map, "selectIssueCount", "selectIssueByPage");
        List<IssueDO> issueDOlist = (List<IssueDO>) result.get("list");

        int badCount = 0;

        String key = null;
        String cookie = null;

        Result codeResult = new ResultSupport(false);

        do {
            codeResult = GetCookieKey.verify();
        } while (!codeResult.isSuccess());

        key = (String) codeResult.getModels().get("key");
        cookie = (String) codeResult.getModels().get("cookie");

        //        logger.info("key=" + key);
        //        logger.info("cookie=" + cookie);

        for (IssueDO issueDO : issueDOlist) {
            try {
                //                int test = issueDO.getId() - (10000 * (pageNo - 1));
                //                if (test < 4000) {
                //                    //                    logger.info("-----mod---issue ----" + issueDO.getId() + "----+" + test);
                //                    continue;
                //                }

                //如果已经置为成功处理，则继续处理下一条
                if (StringUtil.equals(issueDO.getSuccess(), "true")
                    || StringUtil.equals(issueDO.getSuccess(), "wait")) {
                    //                    logger.info("ignore---issue ----" + issueDO.getId());

                    continue;
                }

                Thread.sleep(1000);

                List<WenzhangRecord> recordList = parse(url + issueDO.getUrl() + "&key=" + key,
                    cookie);
                //如果解析有数据，则保存文章，同时修改issue表的状态
                if (recordList != null && recordList.size() > 0) {
                    Thread.sleep(1000);
//                    logger.info("-----ok---issue ----" + issueDO.getId());

                    for (WenzhangRecord wenzhangRecord : recordList) {

                        WenzhangDO wenzhang = new WenzhangDO();
                        wenzhang.setIssueid(getShort(issueDO.getId() + ""));
                        wenzhang.setTitle(getShort(wenzhangRecord.getTitle()));
                        wenzhang.setTitleurl(getShort(wenzhangRecord.getTitleurl()));
                        wenzhang.setAuthor(getShort(wenzhangRecord.getAuthor()));
                        wenzhang.setAbstracturl(getShort(wenzhangRecord.getAbstracturl()));
                        wenzhang.setFulltexturl(getShort(wenzhangRecord.getFulltexturl()));

                        wenzhangDAO.insert(wenzhang);
                        issueDAO.updateSuccess("true", issueDO.getId());
                    }
                } else {
//                    logger.info("no result---issue ----" + issueDO.getId());

                    badCount++;

                    if (badCount > 10) {
//                        logger.info("-----------reget key&cookie--------");
//                        logger.info("badCount=" + badCount);
//                        logger.info("issueDO=" + issueDO.getId());
                        do {
                            codeResult = GetCookieKey.verify();
                        } while (!codeResult.isSuccess());

                        key = (String) codeResult.getModels().get("key");
                        cookie = (String) codeResult.getModels().get("cookie");
                        badCount = 0;
                    }
                }
            } catch (Exception e) {
                logger.info("--------------------Exception ,continue--------------------");
            }
        }

    }

    /**
     *根据URL获取
     * @param url
     * @param cookie
     * @return
     */
    public List<WenzhangRecord> parse(String url, String cookie) {

        SocolarWenzhangParser parser = new SocolarWenzhangParser();

        String content = getWebContent.getSocolarContentHttpURLConnection(url, cookie, false);

        //        System.out.println(content);
        if (StringUtil.isBlank(content)) {
            return null;
        }
        parser.setContent(content);
        return parser.parse();
    }

    private static String getShort(String str) {
        if (StringUtil.isNotBlank(str) && str.length() > 2000) {
            return StringUtil.substring(str, 0, 2000);
        }
        return str;

    }
}
